import React, { useCallback, useRef, useState } from 'react';
import dayjs from 'dayjs';
import {
  Card,
  Form,
  FormInstance,
  Input,
  Space,
  Typography,
  DatePicker,
  Checkbox,
  Affix,
  Button,
  Select,
  Message,
} from '@arco-design/web-react';
import VerificationCode from '@/components/VerificationCode';
import { TYPES } from '@/components/VerificationCode/constant';
import RichTextEditor from '@/components/Quill';
import { useModal } from '@/components/Modal';
import { SSSUpload } from '@/components/upload';
import { useHistory } from 'react-router-dom';
import { raceSaveBasicInfo, raceVerifySmsCode } from '@/services/race';
import { raceType, raceTypeVal } from './constant';
import MapSearch from './MapSearch';
import styles from './index.module.less';

const { Text, Paragraph } = Typography;

const InputWrapperCol = { span: 8 };

export default function Page() {
  const history = useHistory();
  const { showModal } = useModal();
  const formRef = useRef<FormInstance>();
  const [loading, setLoading] = useState(false);
  const [isPublicly, setIsPublicly] = useState(true);
  const [isAgree, setIsAgree] = useState(true);
  const [isTurnMoney, setIsTurnMoney] = useState(true);
  const [detail, setDetail] = useState('');
  const addressData = useRef(null);
  const [addressShow, setAddressShow] = useState('');
  const verifySmsCodeInfo = useRef(null);

  const transferTime = (str: string) => {
    return dayjs(str).hour(12).second(0).format('YYYY-MM-DD HH:mm:ss');
  };

  // 验证手机号
  const beforeVerifySmsCode = async (params: {
    mobile: string;
    type: string;
    code: string;
  }) => {
    let verifyStatus = false;
    if (
      verifySmsCodeInfo.current &&
      verifySmsCodeInfo.current.mobile === params.mobile
    ) {
      // 手机号未更改保存状态
      verifyStatus = true;
    } else {
      try {
        const data = await raceVerifySmsCode(params);
        if (data?.success) {
          verifyStatus = true;
          verifySmsCodeInfo.current = params;
        }
      } catch (error) {
        Message.error(error);
      }
    }
    return verifyStatus;
  };

  const submit = async (data) => {
    const params = {
      sportType: data.sportType, // 赛事类型
      title: data.title, // 赛事名称
      mobile: data.mobile, // 客服咨询电话
      contactWechatQrcodePicUrl:
        data.contactWechatQrcodePicUrl ||
        'group1/M00/67/9D/680fc8d6737a426d905670b22939d734.png', // 客服微信二维码
      applyStartTime: transferTime(data.applyTime[0]), // 报名开始时间（时分秒）
      applyEndTime: transferTime(data.applyTime[1]), // 报名结束时间（时分秒）
      startTime: transferTime(data.raceTime[0]), // 赛事开始时间（时分秒）
      endTime: transferTime(data.raceTime[1]), // 赛事结束时间（时分秒）
      ...addressData.current,
      coverImgUrl:
        data.contactWechatQrcodePicUrl ||
        'group1/M00/67/9D/680fc8d6737a426d905670b22939d734.png', // 赛事海报
      allowRefund: isTurnMoney ? '1' : '0', // 是否允许退款
      refundNote: data.refundNote, // 退款说明
      private_link: isPublicly ? '1' : '0', // 0 不公开
      status: '0', // 表示为草稿
    };
    if (!isAgree) {
      Message.error('请勾选协议');
      return;
    }
    const isCheckPhone = await beforeVerifySmsCode({
      mobile: params.mobile,
      type: '2',
      code: data.smsCode,
    });
    if (!isCheckPhone) {
      return;
    }
    setLoading(true);
    raceSaveBasicInfo({
      basicInfoDTO: params,
      descriptionDO: {
        description: detail,
      },
      normalGroupList: [
        {
          groupType: '1',
          birthEndTime: '2010-12-31',
          price: '298.88',
          quota: '30',
          name: '4岁',
          sort: '1',
          birthStartTime: '2010-01-01',
          isShow: '1',
        },
      ],
    })
      .then(() => {
        Message.success('创建成功');
        history.push('/racing/list');
      })
      .catch((reason) => {
        Message.error(reason);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const handleSubmit = () => {
    formRef.current.validate().then((values) => {
      submit(values);
    });
  };

  const changeAddress = (addressInfo: { [key: string]: string }) => {
    addressData.current = addressInfo;
    formRef.current.setFieldValue('addressAll', addressInfo.addressAll);
  };

  const showMap = useCallback(() => {
    showModal({
      title: null,
      showFooter: false,
      children: <MapSearch changeAddress={changeAddress} />,
      style: {
        width: 900,
        height: 'auto',
      },
    });
  }, [showModal]);

  return (
    <Typography className={styles.container}>
      <Form
        ref={formRef}
        className={styles['form-group']}
        labelAlign="left"
        labelCol={{ span: 3 }}
        scrollToFirstError
      >
        <Card>
          <Typography.Title heading={6} className={styles.title}>
            基本信息
          </Typography.Title>
          <Form.Item
            wrapperCol={InputWrapperCol}
            rules={[{ required: true, message: '赛事类别不能为空' }]}
            label={'赛事类别'}
            field="sportType"
          >
            <Select
              placeholder="请选择赛事类别"
              allowClear
              bordered={false}
              className={styles.select}
              options={[
                ...Object.keys(raceTypeVal).map((key) => {
                  const _key = key as keyof typeof raceTypeVal;
                  return {
                    value: raceTypeVal[_key],
                    label: raceType[raceTypeVal[_key]],
                  };
                }),
              ]}
            />
          </Form.Item>
          <Form.Item
            wrapperCol={InputWrapperCol}
            label={'赛事名称'}
            rules={[{ required: true, message: '赛事名称不能为空' }]}
            field="title"
          >
            <Input placeholder={'请输入赛事名称'} />
          </Form.Item>
          <Form.Item
            wrapperCol={InputWrapperCol}
            rules={[{ required: true, message: '客服咨询电话不能为空' }]}
            label={'客服咨询电话'}
            field="mobile"
          >
            <Input placeholder={'请输入赛事咨询电话'} />
          </Form.Item>
          <Form.Item
            wrapperCol={InputWrapperCol}
            required
            label={'短信验证码'}
            field="mobile"
          >
            <VerificationCode
              containerStyle={{
                width: '100%',
                height: '32px',
                borderRadius: '0',
              }}
              btnStyle={{ fontSize: '12px', width: 'auto', padding: 0 }}
              onPressEnter={handleSubmit}
              formRef={formRef}
              errorMsg="请输入正确的客服咨询电话"
              placeholderMsg="请输入短信验证码"
              textMsg="获取短信验证码"
              type={TYPES.racCreate}
            />
          </Form.Item>
          <Form.Item
            rules={[{ required: false, message: '客服微信二维码不能为空' }]}
            label={'客服微信二维码'}
            field="contactWechatQrcodePicUrl"
          >
            <SSSUpload
              name="上传二维码"
              desc="提示：建议长宽比 1:1，图片小于4M"
            />
          </Form.Item>
          <Form.Item
            required
            label={'报名时间'}
            field="applyTime"
            rules={[{ required: true, message: '请选择报名时间' }]}
          >
            <DatePicker.RangePicker
              allowClear
              showTime
              disabledDate={(date) => dayjs(date).isBefore(dayjs())}
              placeholder={['报名开始时间', '报名结束时间']}
              format={'YYYY-MM-DD HH:mm'}
            />
          </Form.Item>
          <Form.Item
            required
            label={'赛事时间'}
            field="raceTime"
            rules={[{ required: true, message: '请选择赛事时间' }]}
          >
            <DatePicker.RangePicker
              allowClear
              showTime
              disabledDate={(date) => dayjs(date).isBefore(dayjs())}
              placeholder={['赛事开始时间', '赛事结束时间']}
              format={'YYYY-MM-DD HH:mm'}
            />
          </Form.Item>
          <Form.Item
            wrapperCol={InputWrapperCol}
            rules={[{ required: false, message: '赛事地址不能为空' }]}
            label={'赛事地址'}
            field="addressAll"
          >
            <Input
              placeholder={'点击设置赛事地址'}
              onFocus={() => {
                showMap();
              }}
            />
          </Form.Item>
          <Form.Item
            rules={[{ required: false, message: '赛事海报不能为空' }]}
            label={'赛事海报'}
            field="coverImgUrl"
            extra={
              <Paragraph className={styles.poster}>
                <Paragraph>
                  <Checkbox
                    checked={isPublicly}
                    onChange={(val) => setIsPublicly(val)}
                  ></Checkbox>
                </Paragraph>
                <Typography.Text className={styles.text}>
                  公开发布：平台将在赛事列表中展示本场赛事，我们会为您免费宣传，协助推广引流
                </Typography.Text>
              </Paragraph>
            }
          >
            <SSSUpload
              name="上传赛事海报"
              desc="提示：图片尺寸为1125*840px，图片小于4M"
              // width="270px"
              // height="202px"
            />
          </Form.Item>
          <Form.Item required label={'是否支持退款'}>
            <Paragraph className={styles['check-content']}>
              <Checkbox
                checked={isTurnMoney}
                onChange={(val) => setIsTurnMoney(val)}
              ></Checkbox>
              <Paragraph className={styles['check-text']}>
                不支持：此设置会在参赛者报名时展示说明，参赛者不能在小程序中主动申请退款，如需退款需联系主办方处理
              </Paragraph>
            </Paragraph>
          </Form.Item>
          <Form.Item
            rules={[{ required: true, message: '退款说明不能为空' }]}
            label={<Paragraph className={styles['label-col']} />}
            field="refundNote"
            labelAlign="right"
            extra={
              <>
                <Paragraph className={styles['turn-money']}>
                  <Typography.Text>案例:</Typography.Text>
                  <Paragraph className={styles.text}>
                    <Typography.Text className={styles.desc}>
                      1、一旦报名成功后，若因个人原因或其他不可控因素无法按时参赛，不支持取消/退款;
                    </Typography.Text>
                    <Typography.Text className={styles.desc}>
                      2、如赛事出现不可控原因，赛事将会延期举办，报名费不退回:3、如特殊极端场景无法参赛，请联系赛事主办方;
                    </Typography.Text>
                    <Typography.Text className={styles.desc}>
                      3、如特殊极端场景无法参赛，请联系赛事主办方;
                    </Typography.Text>
                  </Paragraph>
                </Paragraph>
              </>
            }
          >
            <Input.TextArea
              placeholder={'请输入退款说明'}
              className={styles['text-area']}
            />
          </Form.Item>
        </Card>
        <Card>
          <Typography.Title heading={6} className={styles.title}>
            普通分组列表
          </Typography.Title>
        </Card>
        <Card>
          <Typography.Title heading={6} className={styles.title}>
            团队分组列表
          </Typography.Title>
        </Card>
        <Card>
          <Typography.Title heading={6} className={styles.title}>
            报名表单
          </Typography.Title>
        </Card>
        <Card style={{ paddingBottom: '60px' }}>
          <Typography.Title heading={6} className={styles.title}>
            赛事详情
          </Typography.Title>
          <RichTextEditor
            value={detail}
            onChange={(val: string) => setDetail(val)}
            // preserveWhitespace // 格式化
            style={{
              height: 410,
            }}
          />
        </Card>
      </Form>
      <Affix offsetBottom={0}>
        <Paragraph className={styles.actions}>
          <Paragraph className={styles.left}>
            <Checkbox
              checked={isAgree}
              onChange={(val) => setIsAgree(val)}
            ></Checkbox>
            <Typography.Text className={styles.normal}>
              我同意并遵守
            </Typography.Text>
            <Typography.Text
              className={styles.rule}
              onClick={() => {
                window.open('/servicerule');
              }}
            >
              《星乐动平台商户服务协议》
            </Typography.Text>
          </Paragraph>
          <Space className={styles.right}>
            <Button onClick={() => handleSubmit()}>保存草稿</Button>
            <Button>预览并生成赛事码</Button>
            <Button
              type="primary"
              className={styles.apply}
              // loading={loading}
              onClick={() => handleSubmit()}
            >
              发布赛事
            </Button>
          </Space>
        </Paragraph>
      </Affix>
    </Typography>
  );
}
